{% extends "base.html" %}

{% block content %}
<div class="max-w-7xl mx-auto">
    <!-- Header -->
    <div class="mb-8 flex items-center justify-between">
        <div>
            <h1 class="text-2xl font-bold text-gray-900">Collections</h1>
            <p class="text-gray-600">Browse documents organized by regulatory authority</p>
        </div>
        <button 
            onclick="openAddCollectionModal()"
            class="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 flex items-center space-x-2"
        >
            <i class="fas fa-plus"></i>
            <span>Add Collection</span>
        </button>
    </div>

    <!-- Collections Grid View -->
    <div id="collectionsGridView">
        <div id="collectionsGrid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <!-- Loading state -->
            <div class="col-span-full text-center py-8">
                <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600 mx-auto"></div>
                <p class="mt-2 text-gray-500">Loading collections...</p>
            </div>
        </div>
    </div>

    <!-- Documents List View (Hidden by default) -->
    <div id="documentsListView" class="hidden">
        <!-- Back Button -->
        <div class="mb-6">
            <button 
                onclick="backToCollections()"
                class="flex items-center space-x-2 text-indigo-600 hover:text-indigo-800"
            >
                <i class="fas fa-arrow-left"></i>
                <span>Back to Collections</span>
            </button>
        </div>

        <!-- Collection Header -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-6">
            <div class="flex items-center justify-between">
                <div>
                    <h2 class="text-xl font-semibold text-gray-900" id="collectionTitle">Collection Name</h2>
                    <p class="text-gray-600" id="collectionDescription">Collection description</p>
                </div>
                <div class="text-right">
                    <p class="text-3xl font-bold text-indigo-600" id="collectionCount">0</p>
                    <p class="text-sm text-gray-500">Documents</p>
                </div>
            </div>
        </div>

        <!-- Search and Filters -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 mb-6">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Search by File Name</label>
                    <input 
                        type="text" 
                        placeholder="Search documents..."
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                        id="documentSearchInCollection"
                    >
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                    <select id="statusFilterInCollection" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500">
                        <option value="">All Status</option>
                        <option value="Draft">Draft</option>
                        <option value="Effective">Effective</option>
                        <option value="Expired">Expired</option>
                    </select>
                </div>
            </div>
        </div>

        <!-- Documents Table -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200">
            <div class="grid grid-cols-12 gap-4 px-6 py-3 bg-gray-50 border-b border-gray-200 text-sm font-medium text-gray-700">
                <div class="col-span-3">File Name</div>
                <div class="col-span-2">Country/Region</div>
                <div class="col-span-2">Regulation ID</div>
                <div class="col-span-2">Issuing Authority</div>
                <div class="col-span-1">Status</div>
                <div class="col-span-2 text-right">Actions</div>
            </div>
            
            <div id="documentsListInCollection"></div>
            
            <div id="loadingStateInCollection" class="p-8 text-center">
                <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600 mx-auto"></div>
                <p class="mt-2 text-gray-500">Loading documents...</p>
            </div>
            
            <div id="emptyStateInCollection" class="hidden p-8 text-center">
                <i class="fas fa-folder-open text-gray-300 text-4xl mb-3"></i>
                <p class="text-gray-500">No documents found in this collection</p>
            </div>
        </div>

        <!-- Pagination -->
        <div class="flex items-center justify-between mt-6">
            <div class="text-sm text-gray-500" id="paginationInfoInCollection">
                Showing <span id="startCountInCollection">0</span> to <span id="endCountInCollection">0</span> of <span id="totalCountInCollection">0</span> documents
            </div>
            <div class="flex space-x-2" id="paginationControlsInCollection"></div>
        </div>
    </div>
</div>

<!-- Add Collection Modal -->
<div id="addCollectionModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
    <div class="bg-white rounded-xl shadow-xl max-w-md w-full mx-4">
        <div class="p-6">
            <h3 class="text-xl font-semibold text-gray-900 mb-4">Add New Collection</h3>
            
            <form id="addCollectionForm">
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">Collection Name <span class="text-red-500">*</span></label>
                    <input 
                        type="text" 
                        id="collectionName"
                        placeholder="e.g., TGA Australia"
                        maxlength="64"
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                        required
                    >
                    <p id="collectionNameError" class="hidden mt-1 text-sm text-red-600"></p>
                </div>
                
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-2">Description</label>
                    <textarea 
                        id="collectionDescription"
                        placeholder="Brief description of this collection"
                        rows="3"
                        maxlength="500"
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                    ></textarea>
                </div>
                
                <div class="flex items-center justify-end space-x-3">
                    <button 
                        type="button"
                        onclick="closeAddCollectionModal()"
                        class="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
                    >
                        Cancel
                    </button>
                    <button 
                        type="submit"
                        class="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700"
                        id="addCollectionButton"
                    >
                        Add Collection
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Success/Error Toast -->
<div id="toast" class="hidden fixed top-4 right-4 z-50"></div>
{% endblock %}

{% block scripts %}
<script>
let currentCollection = null;
let currentPage = 1;
const pageSize = 20;
let totalDocuments = 0;

document.addEventListener('DOMContentLoaded', async () => {
    await loadCollections();
});

async function loadCollections() {
    try {
        const response = await fetch('/api/collections/stats');
        const data = await response.json();
        
        if (data.status === 'success') {
            renderCollectionsGrid(data.collections);
        } else {
            showError('Failed to load collections');
        }
    } catch (error) {
        console.error('Error loading collections:', error);
        showError('Error loading collections');
    }
}

function renderCollectionsGrid(collections) {
    const grid = document.getElementById('collectionsGrid');
    
    if (collections.length === 0) {
        grid.innerHTML = `
            <div class="col-span-full text-center py-8">
                <i class="fas fa-folder-open text-gray-300 text-4xl mb-3"></i>
                <p class="text-gray-500">No collections available</p>
            </div>
        `;
        return;
    }
    
    grid.innerHTML = '';
    
    const colorMap = {
        'blue': 'bg-blue-100 text-blue-600',
        'red': 'bg-red-100 text-red-600',
        'green': 'bg-green-100 text-green-600',
        'purple': 'bg-purple-100 text-purple-600',
        'yellow': 'bg-yellow-100 text-yellow-600',
        'pink': 'bg-pink-100 text-pink-600'
    };
    
    collections.forEach(collection => {
        const colorClass = colorMap[collection.color] || 'bg-gray-100 text-gray-600';
        
        const card = document.createElement('div');
        card.className = 'bg-white rounded-xl shadow-sm border border-gray-200 p-6 hover:shadow-md transition-shadow cursor-pointer';
        card.onclick = () => viewCollection(collection);
        
        card.innerHTML = `
            <div class="flex items-center justify-between mb-4">
                <div class="w-12 h-12 ${colorClass} rounded-lg flex items-center justify-center">
                    <span class="font-semibold">${collection.display_name.substring(0, 5)}</span>
                </div>
                <span class="text-sm text-gray-500">${collection.document_count} docs</span>
            </div>
            <h3 class="font-semibold text-gray-900 mb-2">${collection.display_name}</h3>
            <p class="text-gray-600 text-sm line-clamp-2">${collection.description || 'No description available'}</p>
            <button class="mt-4 text-indigo-600 hover:text-indigo-800 text-sm font-medium flex items-center space-x-1">
                <span>View Documents</span>
                <i class="fas fa-arrow-right text-xs"></i>
            </button>
        `;
        
        grid.appendChild(card);
    });
}

function viewCollection(collection) {
    currentCollection = collection;
    currentPage = 1;
    
    document.getElementById('collectionsGridView').classList.add('hidden');
    document.getElementById('documentsListView').classList.remove('hidden');
    
    document.getElementById('collectionTitle').textContent = collection.display_name;
    document.getElementById('collectionDescription').textContent = collection.description || '';
    document.getElementById('collectionCount').textContent = collection.document_count;
    
    loadDocumentsForCollection();
    setupCollectionEventListeners();
}

function backToCollections() {
    document.getElementById('collectionsGridView').classList.remove('hidden');
    document.getElementById('documentsListView').classList.add('hidden');
    currentCollection = null;
    loadCollections();
}

function setupCollectionEventListeners() {
    let searchTimeout;
    document.getElementById('documentSearchInCollection').addEventListener('input', (e) => {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            currentPage = 1;
            loadDocumentsForCollection();
        }, 300);
    });
    
    document.getElementById('statusFilterInCollection').addEventListener('change', () => {
        currentPage = 1;
        loadDocumentsForCollection();
    });
}

async function loadDocumentsForCollection() {
    try {
        showLoadingState();
        
        const searchQuery = document.getElementById('documentSearchInCollection').value;
        const status = document.getElementById('statusFilterInCollection').value;
        
        const params = new URLSearchParams({
            collection: currentCollection.name,
            page: currentPage,
            limit: pageSize
        });
        
        if (searchQuery) params.append('search', searchQuery);
        if (status) params.append('status', status);
        
        const response = await fetch(`/api/documents?${params}`);
        const data = await response.json();
        
        if (data.status === 'success') {
            totalDocuments = data.total || data.documents.length;
            renderDocuments(data.documents);
            updatePagination();
        } else {
            throw new Error(data.message);
        }
    } catch (error) {
        console.error('Error loading documents:', error);
        showEmptyState('Error loading documents');
    }
}

function renderDocuments(documents) {
    const container = document.getElementById('documentsListInCollection');
    
    if (documents.length === 0) {
        showEmptyState();
        return;
    }
    
    hideEmptyState();
    hideLoadingState();
    
    container.innerHTML = '';
    
    const statusColors = {
        'Draft': 'bg-yellow-100 text-yellow-800',
        'Effective': 'bg-green-100 text-green-800',
        'Expired': 'bg-red-100 text-red-800'
    };
    
    documents.forEach(doc => {
        const row = document.createElement('div');
        row.className = 'grid grid-cols-12 gap-4 px-6 py-4 border-b border-gray-100 hover:bg-gray-50';
        
        const status = doc.status || 'Unknown';
        const statusColor = statusColors[status] || 'bg-gray-100 text-gray-800';
        const displayFileName = doc.file_name || doc.display_name || doc.filename || 'Unknown';
        
        row.innerHTML = `
            <div class="col-span-3">
                <button onclick="viewDocument('${doc._id}')" class="text-indigo-600 hover:text-indigo-800 font-medium text-left">
                    <i class="fas fa-file-alt mr-2"></i>${displayFileName}
                </button>
            </div>
            <div class="col-span-2 text-gray-600">${doc.country || ''}</div>
            <div class="col-span-2 text-gray-600">${doc.regulation_id || '-'}</div>
            <div class="col-span-2 text-gray-600">${doc.issuing_authority || ''}</div>
            <div class="col-span-1">
                <span class="px-2 py-1 text-xs font-medium rounded-full ${statusColor}">
                    ${status}
                </span>
            </div>
            <div class="col-span-2 text-right">
                <div class="flex items-center justify-end space-x-2">
                    <button onclick="viewDocument('${doc._id}')" class="text-blue-600 hover:text-blue-800" title="View">
                        <i class="fas fa-eye"></i>
                    </button>
                    <button onclick="editDocument('${doc._id}')" class="text-green-600 hover:text-green-800" title="Edit">
                        <i class="fas fa-edit"></i>
                    </button>
                </div>
            </div>
        `;
        
        container.appendChild(row);
    });
}

function updatePagination() {
    const start = (currentPage - 1) * pageSize + 1;
    const end = Math.min(currentPage * pageSize, totalDocuments);
    
    document.getElementById('startCountInCollection').textContent = start;
    document.getElementById('endCountInCollection').textContent = end;
    document.getElementById('totalCountInCollection').textContent = totalDocuments;
    
    const controls = document.getElementById('paginationControlsInCollection');
    const totalPages = Math.ceil(totalDocuments / pageSize);
    
    controls.innerHTML = '';
    
    const prevButton = document.createElement('button');
    prevButton.className = `px-3 py-1 border border-gray-300 rounded ${currentPage === 1 ? 'bg-gray-100 text-gray-400 cursor-not-allowed' : 'text-gray-700 hover:bg-gray-50'}`;
    prevButton.innerHTML = '<i class="fas fa-chevron-left"></i>';
    prevButton.disabled = currentPage === 1;
    prevButton.onclick = () => {
        if (currentPage > 1) {
            currentPage--;
            loadDocumentsForCollection();
        }
    };
    controls.appendChild(prevButton);
    
    for (let i = 1; i <= totalPages; i++) {
        if (totalPages <= 7 || i === 1 || i === totalPages || (i >= currentPage - 1 && i <= currentPage + 1)) {
            const pageButton = document.createElement('button');
            pageButton.className = `px-3 py-1 border border-gray-300 ${currentPage === i ? 'bg-indigo-600 text-white' : 'text-gray-700 hover:bg-gray-50'}`;
            pageButton.textContent = i;
            pageButton.onclick = () => {
                currentPage = i;
                loadDocumentsForCollection();
            };
            controls.appendChild(pageButton);
        } else if (i === currentPage - 2 || i === currentPage + 2) {
            const ellipsis = document.createElement('span');
            ellipsis.className = 'px-2 text-gray-400';
            ellipsis.textContent = '...';
            controls.appendChild(ellipsis);
        }
    }
    
    const nextButton = document.createElement('button');
    nextButton.className = `px-3 py-1 border border-gray-300 rounded ${currentPage === totalPages ? 'bg-gray-100 text-gray-400 cursor-not-allowed' : 'text-gray-700 hover:bg-gray-50'}`;
    nextButton.innerHTML = '<i class="fas fa-chevron-right"></i>';
    nextButton.disabled = currentPage === totalPages;
    nextButton.onclick = () => {
        if (currentPage < totalPages) {
            currentPage++;
            loadDocumentsForCollection();
        }
    };
    controls.appendChild(nextButton);
}

function showLoadingState() {
    document.getElementById('loadingStateInCollection').classList.remove('hidden');
    document.getElementById('emptyStateInCollection').classList.add('hidden');
    document.getElementById('documentsListInCollection').innerHTML = '';
}

function hideLoadingState() {
    document.getElementById('loadingStateInCollection').classList.add('hidden');
}

function showEmptyState(message = 'No documents found in this collection') {
    document.getElementById('loadingStateInCollection').classList.add('hidden');
    document.getElementById('documentsListInCollection').innerHTML = '';
    
    const emptyState = document.getElementById('emptyStateInCollection');
    emptyState.querySelector('p').textContent = message;
    emptyState.classList.remove('hidden');
}

function hideEmptyState() {
    document.getElementById('emptyStateInCollection').classList.add('hidden');
}

function showError(message) {
    const grid = document.getElementById('collectionsGrid');
    grid.innerHTML = `
        <div class="col-span-full text-center py-8">
            <i class="fas fa-exclamation-triangle text-red-300 text-4xl mb-3"></i>
            <p class="text-red-500">${message}</p>
        </div>
    `;
}

function viewDocument(docId) {
    window.location.href = `/view/${docId}`;
}

function editDocument(docId) {
    window.location.href = `/edit/${docId}`;
}

// Add Collection Modal Functions
function openAddCollectionModal() {
    document.getElementById('addCollectionModal').classList.remove('hidden');
    document.getElementById('collectionName').value = '';
    document.getElementById('collectionDescription').value = '';
    document.getElementById('collectionNameError').classList.add('hidden');
}

function closeAddCollectionModal() {
    document.getElementById('addCollectionModal').classList.add('hidden');
}

document.getElementById('addCollectionForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const name = document.getElementById('collectionName').value.trim();
    const description = document.getElementById('collectionDescription').value.trim();
    const button = document.getElementById('addCollectionButton');
    
    if (!name) {
        document.getElementById('collectionNameError').textContent = 'Collection name is required';
        document.getElementById('collectionNameError').classList.remove('hidden');
        return;
    }
    
    button.disabled = true;
    button.textContent = 'Adding...';
    
    try {
        const response = await fetch('/api/collections', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ name, description })
        });
        
        const data = await response.json();
        
        if (data.status === 'success') {
            showToast('Collection added successfully', 'success');
            closeAddCollectionModal();
            await loadCollections();
        } else {
            showToast(data.message || 'Failed to add collection', 'error');
        }
    } catch (error) {
        console.error('Error adding collection:', error);
        showToast('Error adding collection', 'error');
    } finally {
        button.disabled = false;
        button.textContent = 'Add Collection';
    }
});

function showToast(message, type = 'success') {
    const toast = document.getElementById('toast');
    const bgColor = type === 'success' ? 'bg-green-50 border-green-200' : 'bg-red-50 border-red-200';
    const textColor = type === 'success' ? 'text-green-800' : 'text-red-800';
    const icon = type === 'success' ? 'fa-check-circle text-green-600' : 'fa-times-circle text-red-600';
    
    toast.innerHTML = `
        <div class="${bgColor} border rounded-lg p-4 shadow-lg flex items-center space-x-3">
            <i class="fas ${icon} text-xl"></i>
            <span class="${textColor} font-medium">${message}</span>
        </div>
    `;
    toast.classList.remove('hidden');
    
    setTimeout(() => {
        toast.classList.add('hidden');
    }, 3000);
}
</script>
{% endblock %}